<template>
    <view :style="'direction:' + $t('dir')" :class="$t('dir') == 'rtl' ? 'rtl' : 'ltr'">
        <navbar :title="$t('qingxuanzequyu')" :back="true" bgLayer="linear-gradient(#CBD6EC, #fff)" navbarBg="linear-gradient(#c8d5ec, #dce4f3)" />
        <view class="main">
            <view class="full-width bg-white py-sm" style="position: sticky; z-index: 999; border-top-left-radius: 40rpx; border-top-right-radius: 40rpx" :style="{ top: headerArea.title_height + headerArea.menuTop + 'px' }">
                <view class="center row items-center" style="background: #f6f6f6; border-radius: 68rpx; width: 90%; margin: 0 5%; border: 1px solid #f2f2f2; padding-top: 22rpx; padding-bottom: 22rpx">
                    <view style="flex: 1; font-size: 22rpx; color: #d8d8d8" :style="$t('dir') == 'rtl' ? 'text-align:right !important' : 'text-align:left !important'">
                        <u--input type="text" inputAlign="center" :customStyle="{ direction: inputDir }" @change="handleInput" :maxlength="32" :placeholder="$t('qingshuruchengshiming')" border="none" v-model="kw" placeholderStyle="text-align:center" fontSize="28rpx" @confirm="searchConfirm()"></u--input>
                    </view>
                    <view class="row row flex-center button" style="width: 180rpx; margin: 0 30rpx" :style="$t('dir') == 'rtl' ? 'border-right: 1rpx solid #ccc;' : 'border-left: 1rpx solid #ccc;'" @click="back">
                        <u-icon name="close" color="item.gray" class="mx-xs" size="13" />
                        <view class="mx-xs">{{ $t('cancel') }}</view>
                    </view>
                </view>
            </view>
            <scroll-view scroll-y="true" scroll-with-animation scroll-anchoring :scroll-into-view="intoId" :show-scrollbar="false" class="swiper-list" :style="'height:calc(100vh - 140rpx - ' + (headerArea.title_height + headerArea.menuTop + 'px') + ')'">
                <view class="bg-white pa-sm" v-if="selectedCity && selectedCity.length > 0">
                    <view class="text-gray pa-sm pt-none">{{ $t('lishixuanze') }}</view>
                    <view class="d-flex" style="flex-flow: column wrap; height: 160rpx; list-style-type: none; width: 90vw; overflow-x: scroll">
                        <view v-for="(item, i) in selectedCity" :key="i" @click="itemSelect(item)" style="min-width: 100rpx; max-width: 200rpx; height: 60rpx; line-height: 60rpx; background: #f6f6f6; border-radius: 8px" class="ml-sm mb-sm text-center px-sm text-nowrap"> {{ item['name' + $t('k')] ? item['name' + $t('k')] : item['name'] || item['name_ug'] }}</view>
                    </view>
                </view>

                <view class="bg-white px-sm">
                    <view class="text-gray pa-sm">{{ $t('remen') }}</view>
                    <view class="d-flex" style="flex-flow: column wrap; height: 160rpx; list-style-type: none; width: 90vw; overflow-x: scroll">
                        <view v-for="(item, i) in recommedList" :key="i" @click="itemSelect(item)" style="min-width: 100rpx; max-width: 200rpx; height: 60rpx; line-height: 60rpx; background: #f6f6f6; border-radius: 8px" class="ml-sm mb-sm text-center px-sm text-nowrap"> {{ item['name' + $t('k')] ? item['name' + $t('k')] : item['name'] || item['name_ug'] }}</view>
                    </view>
                </view>

                <view v-if="detailLoading" class="d-flex flex-center bg-white" style="height: 60%">
                    <u-loading-icon mode="circle" style="width: 18vw; height: 18vw" size="50" color="var(--app-color)" bold></u-loading-icon>
                </view>
                <view class="bg-white pa-sm" v-else>
                    <view class="text-gray pa-sm pb-none">{{ $t('qingshuanzechengshi') }}</view>
                    <view class="area-item" v-for="(item, index) in dataList" :key="index">
                        <text :class="intoId == item._id ? 'area-item-id area-item-id-sticky' : 'area-item-id'" :id="'letter-' + item.code">{{ item._id }}</text>
                        <view class="swiper-list2">
                            <text class="area-item-name" @click="itemSelect(subitem)" v-for="(subitem, j) in item.data" :key="j">
                                {{ subitem['name' + $t('k')] ? subitem['name' + $t('k')] : subitem['name'] || subitem['name_ug'] }}
                            </text>
                        </view>
                    </view>
                </view>
            </scroll-view>

            <view class="slider-right" v-if="!detailLoading">
                <view class="slider-list">
                    <text class="slider-item" :class="$t('dir') == 'rtl' ? 'rtl' : 'ltr'" v-for="(item, index) in dataList" :key="index" @click="sliderSelect(item.code)" :style="'letter-' + item.code == intoId ? 'color:red' : ''" @touchstart="handleTouchStart(item.code)" @touchmove="handleTouchMove(item.code)" @touchend="handleTouchEnd(item.code)">{{ item._id }}</text>
                </view>
            </view>
        </view>
    </view>
</template>
<script>
import { pinyin } from 'pinyin-pro'
export default {
    data() {
        return {
            detailLoading: false,
            intoId: '',
            code: '',
            selectedItem: {
                province: { name: '', name_ug: '', code: '' },
                city: { name: '', name_ug: '', code: '' },
                dis: { name: '', name_ug: '', code: '' },
                town: { name: '', name_ug: '', code: '' },
            },
            inputDir: 'ltr',
            kw: '',
            dataList: [],
            dataListAll: [],
            dataListSorted: [],
            selectedCity: [],
            recommedList: [
                {
                    id: 45998,
                    code: '6501',
                    name: '乌鲁木齐',
                    name_ug: 'ئۈرۈمچى',
                    type: '1',
                },
                {
                    id: 46088,
                    code: '6502',
                    name: '克拉玛依',
                    name_ug: 'قاراماي',
                    type: '1',
                },
                {
                    id: 46112,
                    code: '6521',
                    name: '吐鲁番',
                    name_ug: 'تۇرپان',
                    parent_code: '65',
                    type: '1',
                },
                {
                    id: 46147,
                    code: '6522',
                    name: '哈密',
                    name_ug: 'قۇمۇل',
                    type: '1',
                },
                {
                    id: 46205,
                    code: '6523',
                    name: '昌吉',
                    name_ug: 'سانجى',
                    type: '1',
                },
                {
                    id: 46330,
                    code: '6527',
                    name: '博尔塔拉',
                    name_ug: 'بورتالا',
                    type: '1',
                },
                {
                    id: 46372,
                    code: '6528',
                    name: '巴音郭楞',
                    name_ug: 'بايىنغۇلىن',
                    type: '1',
                },
                {
                    id: 46501,
                    code: '6529',
                    name: '阿克苏',
                    name_ug: 'ئاقسۇ',
                    type: '1',
                },
                {
                    id: 46638,
                    code: '6530',
                    name: '克州',
                    name_ug: 'قىزىلسۇ',
                    type: '1',
                },
                {
                    id: 46697,
                    code: '6531',
                    name: '喀什',
                    name_ug: 'قەشقەر',
                    parent_code: '65',
                    type: '1',
                },
                {
                    id: 46907,
                    code: '6532',
                    name: '和田',
                    name_ug: 'خوتەن',
                    type: '1',
                },
                {
                    id: 47019,
                    code: '6540',
                    name: '伊犁',
                    name_ug: 'غۇلجا',
                    type: '1',
                },
                {
                    id: 47191,
                    code: '6542',
                    name: '塔城',
                    name_ug: 'تارباغاتاي',
                    type: '1',
                },
                {
                    id: 47324,
                    code: '6543',
                    name: '阿勒泰',
                    name_ug: 'ئالتاي',
                    type: '1',
                },
            ],
        }
    },
    onLoad() {
        let selectedCity = uni.getStorageSync('selectedCity')
        if (selectedCity) {
            selectedCity = JSON.parse(selectedCity)
            if (selectedCity && selectedCity.length > 0) {
                this.selectedCity = selectedCity
            }
        }
        this.getCity()
    },
    onShow() {},
    onPullDownRefresh() {
        uni.stopPullDownRefresh()
    },
    computed: {
        headerArea() {
            let area = uni.getSystemInfoSync()
            // #ifdef MP-WEIXIN
            let menu = uni.getMenuButtonBoundingClientRect()

            console.log('area:', area)
            console.log('menu:', menu)

            return {
                status_height: area.statusBarHeight,
                title_height: menu.height + (menu.top - area.statusBarHeight) * 2,
                menuLeft: menu.left,
                menuTop: menu.top - (menu.top - area.statusBarHeight),
            }
            // #endif
            // #ifndef MP-WEIXIN
            return {
                status_height: area.statusBarHeight,
                title_height: uni.upx2px(82),
                menuLeft: 0,
                menuTop: uni.upx2px(88),
            }
            // #endif
        },
    },
    onReachBottom() {},
    methods: {
        itemSelect(item) {
            uni.setStorageSync('location', item)
            let arr = []
            let selectedCity = uni.getStorageSync('selectedCity')
            if (selectedCity) {
                arr = JSON.parse(selectedCity)
                if (arr.length > 0) {
                    let flag = false
                    for (var obj of arr) {
                        if (obj.id == item.id) flag = true
                    }
                    if (!flag) arr.unshift(item)
                }
                uni.setStorageSync('selectedCity', JSON.stringify(arr))
            } else {
                arr.push(item)
                uni.setStorageSync('selectedCity', JSON.stringify(arr))
            }
            this.back()
        },
        getCity() {
            let data = { type: 1 }
            this.detailLoading = true
            this.$uniapi('/city', data)
                .then((res) => {
                    this.detailLoading = false
                    if (res.code == 0) {
                        this.dataListAll = res.data
                        this.dataList = this.groupByFirstLetter(this.dataListAll)
                    }
                })
                .catch((err) => {
                    this.detailLoading = false
                })
        },
        selectItem(item) {
            this.code = item.code
        },
        // 输入监听
        handleInput(event) {
            const str = event
            this.inputDir = this.$tools.strDir(str) //方向
            if (this.kw) {
                this.dataList = this.groupByFirstLetter(this.filterByTwoFields())
            } else {
                this.dataList = this.groupByFirstLetter(this.dataListAll)
            }
        },
        filterByTwoFields() {
            // 使用 filter 方法进行模糊查询
            return this.dataListAll.filter((item) => (item.name_ug && item.name_ug.toString().includes(this.kw)) || (item.name && item.name.toString().includes(this.kw)))
        },

        searchConfirm() {},
        back() {
            let pages = getCurrentPages()
            if (pages.length > 1) {
                // 如果有上一页，就返回上一页
                uni.navigateBack({
                    delta: 1,
                })
            } else {
                //没有上一页，就返回首页
                uni.switchTab({
                    url: '/pages/index/index',
                })
            }
        },
        sliderSelect(id) {
            this.intoId = 'letter-' + id
        },
        groupByFirstLetter(data) {
            let ugAlphabet = ['ئا', 'ئە', 'ب', 'پ', 'ت', 'ج', 'چ', 'خ', 'د', 'ر', 'ز', 'ژ', 'س', 'ش', 'غ', 'ف', 'ق', 'ك', 'گ', 'ڭ', 'ل', 'م', 'ن', 'ھ', 'ئو', 'ئۇ', 'ئۆ', 'ئۈ', 'ۋ', 'ئې', 'ئى', 'ي']
            // 创建一个字母到索引的映射
            const ugAlphabetMap = ugAlphabet.reduce((acc, letter, index) => {
                acc[letter] = index
                return acc
            }, {})
            // 先进行分组
            let grouped = data.reduce((acc, item) => {
                let letter = ''
                if (this.$t('dir') == 'rtl') {
                    for (var obj of ugAlphabet) {
                        let ug = item.name_ug
                        if (ug.substring(0, 2) == obj) {
                            letter = obj
                            break // 找到后退出循环
                        } else if (ug.substring(0, 1) == obj) {
                            // } else {
                            letter = ug.substring(0, 1)
                            break // 找到后退出循环
                        }
                    }
                } else if (this.$t('dir') == 'ltr') {
                    // 使用拼音库将中文转换为拼音
                    const pinyinArray = pinyin(item.name, { toneType: 'none' })
                    // 获取拼音的首字母
                    letter = pinyinArray[0].toUpperCase()
                }
                if (!letter) console.log('letter:', letter)

                let group = {
                    _id: letter,
                    code: item.code,
                    data: [],
                }

                if (!acc.find((g) => g._id === letter)) {
                    acc.push(group)
                } else {
                    group = acc.find((g) => g._id === letter)
                }

                group.data.push(item)
                return acc
            }, [])

            // 对分组进行排序
            if (this.$t('dir') == 'ltr') {
                grouped.sort((a, b) => a._id.localeCompare(b._id))
            } else if (this.$t('dir') == 'rtl') {
                grouped.sort((a, b) => {
                    const indexA = ugAlphabetMap[a._id] !== undefined ? ugAlphabetMap[a._id] : Infinity
                    const indexB = ugAlphabetMap[b._id] !== undefined ? ugAlphabetMap[b._id] : Infinity
                    return indexA - indexB
                })
            }
            console.log('grouped:', grouped)
            return grouped
        },
        handleTouchStart(e) {
            // console.log('handleTouchStart:', e)
        },
        handleTouchMove(e) {
            // console.log('handleTouchMove:', e)
        },
        handleTouchEnd(e) {
            // console.log('handleTouchEnd:', e)
        },
    },
}
</script>
<style lang="scss">
.rtl .slider-right {
    right: auto !important;
    left: 0;
}
.slider-right {
    position: absolute;
    right: 0rpx;
    top: 80rpx;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20rpx;

    .slider-list {
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: #ebe8ee;
        border-radius: 20rpx;
    }

    .slider-item {
        padding: 10rpx 10rpx;
        font-size: 26rpx;
        color: #24292e;

        &:first-child {
            padding-top: 20rpx;
        }

        &:last-child {
            padding-bottom: 20rpx;
        }
    }
    .rtl.slider-item {
        padding: 4rpx 10rpx;
    }
}

.swiper-list {
    display: flex;
    flex-direction: column;
    position: relative;

    .area-item {
        font-size: 30rpx;

        .area-item-id {
            padding: 20rpx 44rpx 0;
            border-bottom: 1rpx solid #f0ecf2;
            font-weight: bold;
            display: block;
        }

        .area-item-id-sticky {
            position: sticky;
            top: 0;
            background-color: #ffffff;
            transition: all 0.1s;
        }

        .swiper-list2 {
            display: flex;
            flex-direction: column;

            .area-item-name {
                padding: 20rpx 40rpx 20rpx;
                font-weight: 400;
            }
        }
    }
}
</style>
